import { config } from './config.js'

class Request {
	constructor() {
		this.baseUrl = config.baseUrl
		this.timeout = config.timeout
		this.header = config.header
	}

	// 请求拦截器
	requestInterceptor(options) {
		// 获取token
		const token = uni.getStorageSync('token')
		if (token) {
			options.header = {
				...options.header,
				'Authorization': `Bearer ${token}`
			}
		}
		return options
	}

	// 响应拦截器
	responseInterceptor(response) {
		const { statusCode, data } = response
		
		// 请求成功
		if (statusCode === 200) {
			return data
		}
		
		// 401：未登录或token过期
		if (statusCode === 401) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			// 清除token
			uni.removeStorageSync('token')
			// 跳转登录页
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}, 1500)
			return Promise.reject(response)
		}
		
		// 其他错误
		uni.showToast({
			title: data.message || '请求失败',
			icon: 'none'
		})
		return Promise.reject(response)
	}

	// 请求方法
	request(options) {
		// 合并配置
		options.url = this.baseUrl + options.url
		options.timeout = this.timeout
		options.header = { ...this.header, ...options.header }
		
		// 请求拦截
		options = this.requestInterceptor(options)
		
		// 发起请求
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				success: (res) => {
					resolve(this.responseInterceptor(res))
				},
				fail: (err) => {
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					})
					reject(err)
				}
			})
		})
	}

	// GET请求
	get(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'GET',
			...options
		})
	}

	// POST请求
	post(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'POST',
			header: {
				'Content-Type': 'application/json'
			},
			...options
		})
	}

	// PUT请求
	put(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'PUT',
			...options
		})
	}

	// DELETE请求
	delete(url, data = {}, options = {}) {
		return this.request({
			url,
			data,
			method: 'DELETE',
			...options
		})
	}
}

export const http = new Request() 